import java.util.*;
/**
 *
 * Created with IntelliJ IDEA.
 * Description:
 * User: 62536
 * Date: 2024-02-27
 * Time: 9:00
 */
public class PriorityQueue {
    public int[] elem;
    public int usedSize;

    public PriorityQueue(int[] elem) {
        this.elem = elem;
        usedSize += elem.length;
    }

    public void createBigHeap() {
        for (int parent = (usedSize-1-1)/2; parent >= 0; parent--) {
            siftDown(parent, usedSize);
        }
    }

    //向下调整
    private void siftDown(int parent,int end) {
        int child = 2*parent+1;
        while (child < end) {
            if(child + 1 < usedSize && elem[child] < elem[child+1]) {
                child++;
            }
            //child一定是 左右孩子最大值的下标
            if(elem[child] > elem[parent]) {
                //交换
                swap(child,parent);
                parent = child;
                child = 2*parent+1;
            }else {
                break;
            }
        }
    }
    private void swap(int i,int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }

    //插入
    public void offer(int val) {
        //1.判断满
        if(isFull()) {
            //扩容
            this.elem = Arrays.copyOf(elem,2*elem.length);
        }
        //2、插入元素
        elem[usedSize] = val;
        usedSize++;
        //3、开始向上调整
        shiftUp(usedSize-1);
    }


    private void shiftUp(int child) {
        int parent = (child-1)/2;
        while (child > 0) {
            if(elem[child] > elem[parent]) {
                swap(child,parent);
                child = parent;
                parent = (child-1)/2;
            }else {
                break;
            }
        }
    }
    //删除
    public int poll() {
        int tmp = elem[0];
        swap(0,usedSize-1);
        usedSize--;
        siftDown(0,usedSize);
        return tmp;
    }


    public boolean isFull() {
        return usedSize == elem.length;
    }


    /**
     * 时间复杂度：
     * O(N*logN)
     * 空间复杂度是O(1)
     */
    public void heapSort() {
        int end = usedSize-1;
        while (end > 0) {
            swap(0,end);
            siftDown(0,end-1);
            end--;
        }
    }
    public boolean isEmpty() {

        return usedSize == 0;
    }

    /**
     * 获取堆顶元素
     * @return
     */
    public int peekHeap() {
        if(usedSize == 0) {
            return -1;
        }

        return elem[0];
    }

}
